package com.gd.transfer.nio;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

/**
 * @author du_tian_jie
 * @version v1.0
 * @date 2018/12/22 15:42
 * @desc:
 */
public class Myservice{

 private ServerSocketChannel serverSocketChannel;
 private Selector selector;

 private Logger log = LoggerFactory.getLogger(Myservice.class);

 public void initServerSocketChannel(){
     try {
//         获取servesocketchannel
         serverSocketChannel = ServerSocketChannel.open();
//         绑定端口
         serverSocketChannel.bind(new InetSocketAddress(36000));
//         切换为非阻塞
         serverSocketChannel.configureBlocking(false);
//         获取选择器
         selector = Selector.open();
//         绑定监听事件
         serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

         while (true){
//             监听事件
            if( selector.select()>0){
//                获取选择键集合
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
//
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
//                遍历
                while (iterator.hasNext()) {
                    SelectionKey selectionKey = iterator.next();
//                    判断事件的类型  -> 如果是一个接受事件
                    if(selectionKey.isAcceptable()) {
//                        获取对应的serversocketChannel
                        ServerSocketChannel schannel = (ServerSocketChannel) selectionKey.channel();
//                        接受连接请求 获取对应的sockechannel
                        SocketChannel channel = schannel.accept();
//                        channel设置为非阻塞
                        channel.configureBlocking(false);
//                        注册到选择器上一个读事件
                        channel.register(selector, SelectionKey.OP_READ);
//                        如果是一个可读的事件
                    }else if(selectionKey.isReadable()) {
                        SocketChannel channelr = (SocketChannel) selectionKey.channel();
//                        准备一个bytebeffer
                        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                        int len = 0;
                        while((len=channelr.read(byteBuffer))>0){
//                            切换为写模式
                            byteBuffer.flip();
                            log.info(new String (byteBuffer.array(),0,len,"utf-8"));

                        }

                    }
//                    移除该选择器
                    iterator.remove();
                }

            }
         }


     } catch (IOException e) {
         e.printStackTrace();
     }

 }

}
